﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Eassets.Layered.Domain.Asset;
using Eassets.Service.Asset;
using Eassets.Service.Global;
using Eassets.Layered.Domain.Global;
using Eassets.Service;
using Eassets.Layered.Domain;
using System.Text.RegularExpressions;
using System.Configuration;

namespace Eassets.UI.Asset
{
    public partial class AssetsRequisitionsForm : System.Web.UI.Page
    {
        private Boolean addNew = true;
        DataSet dsMain = new DataSet();
        private DataTable tb;
        private string actionStatus = "Load";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                gridViewARNItemDetails.DataSource = null;
                gridViewARNItemDetails.DataBind();

                DataBindToFixedAssets();
                DisableFields();

                GetRequestingOrganizationLevel();
                GetRequestingPerson();
                GetIssuingOrganizationLevel();
                GetTransactions();
                GetAllMainCategory();

            }
        }

        private void GetRequestingOrganizationLevel()
        {
            OrganizationLevelListService organizationLevelListService = new OrganizationLevelListService();
            List<OrganizationLevelList> organizationLevelLists = new List<OrganizationLevelList>();
            organizationLevelLists =
                organizationLevelListService.GetAllOrganizationLevelList().Where(x => x.OrganizationLevelMode == "B").
                    ToList();
            dropDownListRequestingOrganizationLevel.DataSource = organizationLevelLists;
            dropDownListRequestingOrganizationLevel.DataValueField = "OrganizationLevelListId";
            dropDownListRequestingOrganizationLevel.DataTextField = "Code";
            dropDownListRequestingOrganizationLevel.DataBind();
        }

        private void GetRequestingPerson()
        {
            long empId = Convert.ToInt64(Session["LoggedUserId"]);

            EmployeeService employeeService = new EmployeeService();
            List<Employee> employees = new List<Employee>();
            //Employees = EmployeeService.GetAllEmployee().Where(x => x.EmployeeType == "Supplier" && x.EmployeeId == Convert.ToInt64(Session["loggedEmployeeId"])).ToList();
            employees =
                employeeService.GetAllEmployee().Where(x => x.EmployeeId == empId)
                    .ToList();

            dropDownListRequestingPerson.DataSource = employees;
            dropDownListRequestingPerson.DataValueField = "EmployeeId";
            dropDownListRequestingPerson.DataTextField = "EmployeeName";
            dropDownListRequestingPerson.DataBind();
        }

        private void GetIssuingOrganizationLevel()
        {
            OrganizationLevelListService organizationLevelListService = new OrganizationLevelListService();
            List<OrganizationLevelList> organizationLevelLists = new List<OrganizationLevelList>();
            organizationLevelLists =
                organizationLevelListService.GetAllOrganizationLevelList().Where(
                    x => x.OrganizationLevelMode == "B" && x.Code == "GAM").ToList();

            dropDownListIssuingOrganizationLevel.DataSource = organizationLevelLists;
            dropDownListIssuingOrganizationLevel.DataValueField = "OrganizationLevelListId";
            dropDownListIssuingOrganizationLevel.DataTextField = "Code";
            dropDownListIssuingOrganizationLevel.DataBind();
        }

        private void GetTransactions()
        {
            TransactionService transactionService = new TransactionService();
            List<Transaction> transactionList = new List<Transaction>();

            if (dropDownListRequestingOrganizationLevel.SelectedValue != "0")
            {
                transactionList =
                    transactionService.GetAllTransaction().Where(
                        x =>
                        x.OrganizationLevelListId ==
                        Convert.ToInt64(dropDownListRequestingOrganizationLevel.SelectedValue)).ToList();

                dropDownListTransactionNo.DataSource = transactionList;
                dropDownListTransactionNo.DataValueField = "TransactionId";
                dropDownListTransactionNo.DataTextField = "TransactionNo";
                dropDownListTransactionNo.DataBind();
            }
        }

        private void GetAllMainCategory()
        {
            CategoryService categoryService = new CategoryService();
            try
            {
                if (hiddenFieldMainCategory.Value != "0" || hiddenFieldMainCategory.Value != "")
                {
                    dropDownListMainCategory.DataSource =
                        categoryService.GetAllAssetCategory().Where(x => x.ParentId == 0).ToList();

                    dropDownListMainCategory.DataValueField = "CategoryId";
                    dropDownListMainCategory.DataTextField = "Description";
                    dropDownListMainCategory.DataBind();
                }
                else
                {
                    hiddenFieldMainCategory.Value = "0";
                }

            }
            catch (Exception exception)
            {
                throw;
            }
        }

        private void GetSubCategory()
        {
            CategoryService categoryService = new CategoryService();
            List<Category> category = new List<Category>();

            try
            {
                if (hiddenFieldMainCategory.Value != "0")
                {
                    category =
                        categoryService.GetAllAssetCategory().Where(
                            x => x.ParentId == Convert.ToInt64(hiddenFieldMainCategory.Value)).ToList();

                    dropDownListSubCategory.DataSource = category;
                    dropDownListSubCategory.DataValueField = "CategoryId";
                    dropDownListSubCategory.DataTextField = "Description";
                    dropDownListSubCategory.DataBind();
                }
                else
                {
                    hiddenFieldSubCategory.Value = "0";
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        private void GetAsset()
        {
            AssetService assetService = new AssetService();
            List<Assets> assets = new List<Assets>();

            try
            {
                if (hiddenFieldSubCategory.Value != "0")
                {
                    assets =
                        assetService.GetAllAsset().Where(
                            x => x.AssetCategoryId == Convert.ToInt64(hiddenFieldSubCategory.Value)).ToList();

                    dropDownListAsset.DataSource = assets;
                    dropDownListAsset.DataValueField = "AssetId";
                    dropDownListAsset.DataTextField = "Code";
                    dropDownListAsset.DataBind();
                }
                else
                {
                    hiddenFieldAsset.Value = "0";
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        protected void dropDownListRequestingOrganizationLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dropDownListRequestingOrganizationLevel.SelectedValue == "0")
            {
                //dropDownListTransactionNo.SelectedValue = "0";
                //dropDownListTransactionNo.DataSource = null;
                //dropDownListTransactionNo.DataBind();
                EmptyDataBindToDropDownList(dropDownListTransactionNo);
            }
            else
            {
                GetTransactions();
            }
        }

        protected void dropDownListMainCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dropDownListMainCategory.SelectedValue == "0")
            {
                hiddenFieldMainCategory.Value = "";
                hiddenFieldSubCategory.Value = "";
                EmptyDataBindToDropDownList(dropDownListSubCategory);
            }
            else
            {
                hiddenFieldMainCategory.Value = dropDownListMainCategory.SelectedValue;
                GetSubCategory();
            }
        }

        protected void dropDownListSubCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dropDownListSubCategory.SelectedValue == "0")
            {
                hiddenFieldSubCategory.Value = "";
                hiddenFieldAsset.Value = "";
                EmptyDataBindToDropDownList(dropDownListAsset);
            }
            else
            {
                hiddenFieldSubCategory.Value = dropDownListSubCategory.SelectedItem.Value;
                GetAsset();
            }
        }

        protected void dropDownListAsset_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dropDownListAsset.SelectedValue == "0")
            {
                hiddenFieldAsset.Value = "";
            }
            else
            {
                hiddenFieldAsset.Value = dropDownListAsset.SelectedItem.Value;
            }
            //hiddenFieldAsset.Value = dropDownListAsset.SelectedValue == "0" ? "" : dropDownListAsset.SelectedItem.Value;
        }

        protected void dropDownListTransactionNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            TransactionService transactionService = new TransactionService();
            List<Transaction> transactionList = new List<Transaction>();
            //AssetRequisitionDetailService assetRequisitionDetailService = new AssetRequisitionDetailService();

            if (dropDownListTransactionNo.SelectedValue != "0")
            {
                transactionList =
                    transactionService.GetAllTransaction().Where(
                        x => x.TransactionNo == dropDownListTransactionNo.SelectedItem.Text).ToList();

                foreach (Transaction transaction in transactionList)
                {
                    textBoxStatus.Text = transaction.TransactionStatus;
                    textBoxTransactionDate.Text = Convert.ToString(transaction.TransactionDate);
                    //dropDownListRequestingPerson.SelectedItem = transaction.TransactionUserId;
                    //dropDownListIssuingOrganizationLevel.SelectedValue = "1";
                    DataBindTogridViewTransactionARN(transaction.TransactionNo);
                }
                ButtonAdd.Enabled = false;
                ButtonApply.Enabled = false;
                DisableFields();
                gridViewARNItemDetails.Visible = false;
                gridViewTransactionARN.Visible = true;
            }
            else
            {
                ButtonAdd.Enabled = true;
                gridViewARNItemDetails.Visible = true;
                gridViewTransactionARN.Visible = false;
            }
        }

        private void EnableFields()
        {
            dropDownListMainCategory.Enabled = true;
            dropDownListSubCategory.Enabled = true;
            dropDownListAsset.Enabled = true;
            textBoxQuantity.Enabled = true;
        }

        private void DisableFields()
        {
            dropDownListMainCategory.Enabled = false;
            dropDownListSubCategory.Enabled = false;
            dropDownListAsset.Enabled = false;
            textBoxQuantity.Enabled = false;
        }

        private void SetFieldsToDefault()
        {
            dropDownListMainCategory.SelectedValue = "0";
            dropDownListSubCategory.SelectedValue = "0";
            dropDownListAsset.SelectedValue = "0";
            textBoxQuantity.Text = string.Empty;
        }

        private void EmptyDataBindToDropDownList(DropDownList dropDownList)
        {
            dropDownList.DataSource = null;
            dropDownList.DataBind();
        }

        protected void ButtonAdd_Click(object sender, EventArgs e)
        {
            actionStatus = "Add";

            EnableFields();
            ButtonAdd.Enabled = false;
            ButtonApply.Enabled = true;

        }

        protected void ButtonApply_Click(object sender, EventArgs e)
        {
            actionStatus = "Apply";

            tb = CreateARNDetailsDataTable();
            DataBindToFixedAssets();

            DisableFields();
            SetFieldsToDefault();
            ButtonApply.Enabled = false;
            ButtonAdd.Enabled = true;

        }

        protected void ButtonSave_Click(object sender, EventArgs e)
        {
            actionStatus = "Save";

            TransactionSerialService transactionSerialService = new TransactionSerialService();
            try
            {
                AddDataToTransaction();
                AddDataToAssetRequisitionDetail();
                transactionSerialService.UpdateTransactionSerial("ARN");

            }
            catch (Exception ex)
            {
                throw;
            }
        }

        protected void ButtonConfirm_Click(object sender, EventArgs e)
        {
            string confirmationStatus = "Active";

            int noOfRows = gridViewARNItemDetails.Rows.Count;
            for (int i = 0; i < noOfRows; i++)
            {
                TransactionService transactionService = new TransactionService();
                AssetRequisitionDetailService assetRequisitionDetailService = new AssetRequisitionDetailService();
                string selectedAssetCode = gridViewARNItemDetails.Rows[i].Cells[3].Text;

                string currentStatus = transactionService.GetTransactionStatusByAssetCode(selectedAssetCode);
                long selectedAssetId = assetRequisitionDetailService.GetAssetIdByAssetCode(selectedAssetCode);

                if (currentStatus == "A")
                {
                    confirmationStatus = "ToConfirm";
                    ChangeStatusToConfirm(selectedAssetId);

                }
                else if (currentStatus == "C")
                {
                    confirmationStatus = "Confirmed";

                    FlashMessage1.Message = "Transaction is already confirmed";
                    FlashMessage1.CssClass = "errormessage";
                    FlashMessage1.Display();
                }
            }

            if (confirmationStatus == "ToConfirm")
            {
                SendAuthorizationRequestMail(ViewState["TransactionNo"].ToString());

                FlashMessage1.Message = "Mail sent successfully";
                FlashMessage1.CssClass = "okmessage";
                FlashMessage1.Display();
            }
            else
            {
                FlashMessage1.Message = "Mail sending Failed";
                FlashMessage1.CssClass = "errormessage";
                FlashMessage1.Display();
            }
        }

        private DataTable CreateARNDetailsDataTable()
        {
            DataTable dt = new DataTable("Details");

            dt.Columns.Add("Category");
            dt.Columns.Add("SubCategory");
            dt.Columns.Add("Asset");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("UnitofMeasure");

            return dt;
        }

        private void DataBindToFixedAssets()
        {
            if (dropDownListTransactionNo.SelectedValue == "0")
            {
                try
                {
                    DataRow dr = tb.NewRow();
                    dr["Category"] = dropDownListMainCategory.SelectedItem;
                    dr["SubCategory"] = dropDownListSubCategory.SelectedItem;
                    dr["Asset"] = dropDownListAsset.SelectedItem;
                    dr["Quantity"] = textBoxQuantity.Text;
                    dr["UnitofMeasure"] = "NOS";

                    GridToDT(gridViewARNItemDetails);

                    tb.Rows.Add(dr);
                    gridViewARNItemDetails.DataSource = tb;
                    gridViewARNItemDetails.DataBind();
                }
                catch (Exception ex)
                {

                }
            }
            else
            {

            }
        }

        private void GridToDT(GridView gv)
        {
            DataTable dt = new DataTable("Details");

            dt.Columns.Add("Category");
            dt.Columns.Add("SubCategory");
            dt.Columns.Add("Asset");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("UnitofMeasure");

            foreach (GridViewRow row in gv.Rows)
            {
                DataRow dtrow = tb.NewRow();

                dtrow[0] = row.Cells[1].Text;
                dtrow[1] = row.Cells[2].Text;
                dtrow[2] = row.Cells[3].Text;
                dtrow[3] = row.Cells[4].Text;
                dtrow[4] = row.Cells[5].Text;

                tb.Rows.Add(dtrow);
            }

            //return dt;
        }

        private void AddDataToTransaction()
        {
            string progress = "Fail";

            if (actionStatus == "Save")
            {
                TransactionService transactionService = new TransactionService();
                Transaction transaction = new Transaction();

                transaction.TransactionTypeCode = Convert.ToString("FARQT");
                transaction.TransactionDocumentCode = Convert.ToString("ARN");
                transaction.CompanyId = 0;
                transaction.OrganizationLevelListId = Convert.ToInt64(dropDownListRequestingOrganizationLevel.SelectedValue);
                int serial = Getserial();
                string transactionNo = Convert.ToString(CreateNewTransactionCode((serial + 1)));
                dropDownListTransactionNo.Items.Add(transactionNo);
                //textBoxTransactionNo.Text = Convert.ToString(CreateNewTransactionCode((serial + 1)));

                //transaction.TransactionNo = "GAM/PRN/20120830/000001";
                //transaction.TransactionNo = (textBoxTransactionNo.Text).Trim();
                transaction.TransactionNo = transactionNo;
                ViewState["TransactionNo"] = transaction.TransactionNo;
                transaction.TransactionUserId = Convert.ToInt64(dropDownListRequestingPerson.SelectedValue);
                transaction.TransactionStatus = "A";
                transaction.TransactionDate = DateTime.Now;

                transactionService.AddTransaction(transaction);
                //long transactionId = transactionService.AddTransaction(transaction);

                progress = "Success";
            }

            if (progress == "Success")
            {
                FlashMessage1.Message = "AddDataToTransaction is Successful";
                FlashMessage1.CssClass = "okmessage";
                FlashMessage1.Display();
            }
            else
            {
                FlashMessage1.Message = "AddDataToTransaction is Failed";
                FlashMessage1.CssClass = "errormessage";
                FlashMessage1.Display();
            }
        }

        private void AddDataToAssetRequisitionDetail()
        {
            string progress = "Fail";

            if (actionStatus == "Save")
            {
                AssetRequisitionDetailService assetRequisitionDetailService = new AssetRequisitionDetailService();
                AssetRequisitionDetail assetRequisitionDetail = new AssetRequisitionDetail();

                TransactionService transactionService = new TransactionService();
                long transactionId = transactionService.GetMaxTransactionId();

                //GridViewRow row = gridViewARNItemDetails.SelectedRow;

                //if (row.Cells.Count > 1)
                //{
                int noOfRows = gridViewARNItemDetails.Rows.Count;
                for (int i = 0; i < noOfRows; i++)
                {
                    string selectedAssetCode = gridViewARNItemDetails.Rows[i].Cells[3].Text;
                    long selectedAssetId = assetRequisitionDetailService.GetAssetIdByAssetCode(selectedAssetCode);

                    //List<AssetRequisitionDetail> existAssetRequisitionDetailList =
                    //    assetRequisitionDetailService.GetAllAssetRequisitionDetail().Where(x => x.AssetId == selectedAssetId)
                    //        .ToList();
                    //if (existAssetRequisitionDetailList.Count < 1)
                    //{
                    assetRequisitionDetail.TransactionId = transactionId;
                    assetRequisitionDetail.RequestingOrganizationLevelId =
                        Convert.ToInt64(dropDownListRequestingOrganizationLevel.SelectedValue);
                    assetRequisitionDetail.IssuingOrganizationLevelId =
                        Convert.ToInt64(dropDownListIssuingOrganizationLevel.SelectedValue);
                    assetRequisitionDetail.RequestingEmpId = Convert.ToInt64(dropDownListRequestingPerson.SelectedValue);
                    assetRequisitionDetail.AssetId = selectedAssetId;
                    assetRequisitionDetail.Quantity = Convert.ToInt16(gridViewARNItemDetails.Rows[i].Cells[4].Text);
                    assetRequisitionDetail.Status = "A";
                    assetRequisitionDetail.UnitOfMeasure = "NOS";
                    assetRequisitionDetail.TransactionDate = DateTime.Today;

                    assetRequisitionDetailService.AddAssetRequisitionDetail(assetRequisitionDetail);
                    //}
                    //else
                    //{
                    //    assetRequisitionDetail.Quantity = Convert.ToInt16(gridViewARNItemDetails.Rows[i].Cells[4].Text);
                    //    //assetRequisitionDetail.TransactionDate = DateTime.Today;

                    //    assetRequisitionDetailService.ModifyAssetRequisitionDetail(assetRequisitionDetail);
                    //}
                    progress = "Success";
                }
            }

            if (progress == "Success")
            {
                FlashMessage1.Message = "AddDataToAssetRequisitionDetail is Successful";
                FlashMessage1.CssClass = "okmessage";
                FlashMessage1.Display();
            }
            else
            {
                FlashMessage1.Message = "AddDataToAssetRequisitionDetail is Failed";
                FlashMessage1.CssClass = "errormessage";
                FlashMessage1.Display();
            }
        }

        protected void ChangeStatusToConfirm(long selectedAssetId)
        {
            long selectedTransactionId = 0;

            AssetRequisitionDetailService assetRequisitionDetailService = new AssetRequisitionDetailService();
            List<AssetRequisitionDetail> assetRequisitionDetailList = new List<AssetRequisitionDetail>();
            assetRequisitionDetailList =
                assetRequisitionDetailService.GetAllAssetRequisitionDetail().Where(
                    x => x.AssetId == selectedAssetId).ToList();
            foreach (AssetRequisitionDetail assetRequisitionDetail in assetRequisitionDetailList)
            {
                selectedTransactionId = assetRequisitionDetail.TransactionId;

                assetRequisitionDetail.Status = "C";
                assetRequisitionDetailService.ModifyAssetRequisitionDetail(assetRequisitionDetail);
            }

            TransactionService transactionService = new TransactionService();
            List<Transaction> transactionList = new List<Transaction>();
            transactionList =
                transactionService.GetAllTransaction().Where(x => x.TransactionId == selectedTransactionId).
                    ToList();
            foreach (Transaction transaction in transactionList)
            {
                transaction.TransactionStatus = "C";
                transactionService.ModifyTransaction(transaction);
            }
        }

        private String CreateNewTransactionCode(int maxSerial)
        {
            string maxSerialFormated;
            maxSerialFormated = CreateNumberFormat(Convert.ToInt16(maxSerial));
            Regex regex = new Regex("-");
            string locationCode = dropDownListRequestingOrganizationLevel.SelectedItem.Text;
            string[] arrayParameters = regex.Split(locationCode);
            String yearMonth = DateTime.Now.ToString("yyyyMM");

            string OrganizationLevelListCode = Convert.ToString(arrayParameters[0]);

            string NewTransactionCode = (OrganizationLevelListCode + "/"
                                     + "ARN" + "/"
                                     + yearMonth + "/"
                                   + maxSerialFormated);
            return NewTransactionCode;
        }

        private String CreateNumberFormat(Int16 maxSerial)
        {
            string maxSerialCode;
            if ((maxSerial / 10) == 0)
            {
                maxSerialCode = "0000" + maxSerial;
            }
            else if ((maxSerial / 100) == 0)
            {
                maxSerialCode = "000" + maxSerial;
            }
            else if ((maxSerial / 1000) == 0)
            {
                maxSerialCode = "00" + maxSerial;
            }
            else if ((maxSerial / 10000) == 0)
            {
                maxSerialCode = "0" + maxSerial;
            }
            else
            {
                maxSerialCode = maxSerial.ToString();
            }
            return maxSerialCode;
        }

        private int Getserial()
        {
            long transactionSerial = 0;
            TransactionSerialService transactionSerialService = new TransactionSerialService();

            transactionSerial = transactionSerialService.GetMaxTransactionSerialByWorkFlowDocumentCode("ARN");
            return Convert.ToInt16(transactionSerial);
        }

        protected void gridViewARNItemDetails_SelectedIndexChanged(object sender, GridViewSelectEventArgs e)
        {
            long assetId = Convert.ToInt64(gridViewARNItemDetails.Rows[e.NewSelectedIndex].Cells[3].Text);
            //lblErr.Text = strDept;
        }

        private void SendAuthorizationRequestMail(string transactionNumber)
        {
            try
            {
                Mail mail = new Mail();
                MailService mailService = new MailService();

                EmployeeService employeeService = new EmployeeService();
                Employee employee = new Employee();
                employee = employeeService.GetByIdEmployee(Convert.ToInt64(dropDownListRequestingPerson.SelectedItem.Value));

                AssetRequisitionDetailService assetRequisitionDetailService = new AssetRequisitionDetailService();
                List<Employee> authorizedEmpList =
                    assetRequisitionDetailService.GetEmployeesInAuthorizationGroups().ToList();
                foreach (Employee authorizedEmp in authorizedEmpList)
                {
                    mail.To = authorizedEmp.Email;
                    mail.From = employee.Email;
                    mail.ToName = authorizedEmp.EmployeeName;
                    mail.FromName = ConfigurationManager.AppSettings["SystemName"] + " System Administrator";
                    mail.Subject = "Transaction Authorization";
                    mail.Body = "Your authorization is required for Transactions of :" + transactionNumber +
                                "Please follow the below Link to make Authorization ...." + "http://localhost/eAsset/Asset/ARNAuthorizationForm.aspx";

                    mailService.SendMail(mail, mail.From);
                }

            }
            catch (Exception)
            {
                throw;
            }


        }

        private void DataBindTogridViewTransactionARN(string transactionNo)
        {
            AssetRequisitionDetailService assetRequisitionDetailService = new AssetRequisitionDetailService();
            List<AssetRequisitionDetail> assetRequisitionDetailsList = new List<AssetRequisitionDetail>();
            try
            {
                assetRequisitionDetailsList =
                                assetRequisitionDetailService.GetARNDetailsByTransactionNo(transactionNo).ToList();

                gridViewTransactionARN.DataSource = assetRequisitionDetailsList;
                gridViewTransactionARN.DataBind();
            }
            catch (Exception)
            {

                throw;
            }

        }
    }
}